package org.javapict;

import java.util.HashMap;
import org.deuce.*;

/* connections : a HashMap that keeps track of all the connections of this _Process
 * */

//@SuppressWarnings("rawtypes")
public class _Process{
	protected HashMap<_Channel, _Process> connections = new HashMap<_Channel, _Process>();
	
	//@SuppressWarnings("unchecked")
	@Atomic
	public void addConnnection(_Channel c, _Process p){
		this.connections.put(c, p);
		
		p.addSecondConnnection(c, this);
		return;
	}
	@Atomic
	private void addSecondConnnection(_Channel c, _Process p) {
		// TODO Auto-generated method stub
		this.connections.put(c, p);
		
	}
	@Atomic
	public void removeConnection(_Channel c){
		connections.remove(c);
		return;
	}
	//@Atomic
	public void send(_Channel c, _Message msg){
		while(c.Send(msg)==false){
			//System.out.println("in _Process.send");
			long current = System.currentTimeMillis();
			long future = current+1000;
			while(System.currentTimeMillis() < future){}
		}
		return;
	}
	//@Atomic
	public void receive(_Channel c, _Message msg){
		while(c.Receive(msg)==false){
			//System.out.println("in _Process.receive");
			long current = System.currentTimeMillis();
			long future = current+1000;
			while(System.currentTimeMillis() < future){}
		}
		return;
	}
	public void run(){
		return;
	}
	public void parallel(_Process p1, _Process p2){
		ProcThread thread1 = new ProcThread(p1);
		ProcThread thread2 = new ProcThread(p2);
		thread1.start();
		thread2.start();
	}
	public void choice(_Process p1, _Process p2){
		double random_num = Math.random();
		if(random_num < 0.5) p1.run();
		else p2.run();
	}
}

class ProcThread extends Thread{
	_Process p;
	public ProcThread(_Process proc){
		p = proc;
	}
	@Override
	public void run(){
		p.run();
	}
}

